package org.lc.oauth.extension.filter;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.json.JSONUtil;
import io.micrometer.common.lang.NonNull;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.lc.oauth.vo.LcUserDetails;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.base.domain.JwtUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;


@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    private SecurityContextRepository securityContextRepository;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        String userStr = request.getHeader(AuthConstant.HEADER_USER);
        if (userStr != null) {
            var result = URLDecoder.decode(userStr, StandardCharsets.UTF_8);
            JwtUser jwtUser = JSONUtil.toBean(result, JwtUser.class);
            if (ObjUtil.isNotNull(jwtUser.getUsername())) {
                var userDetails = new LcUserDetails(
                        jwtUser.getClientId(),
                        jwtUser.getUserId(),
                        "test",
                        jwtUser.getUsername(),
                        jwtUser.getNickName(),
                        jwtUser.isSuperAdmin(), jwtUser.getRoles(),
                        jwtUser.getAcls(),
                        jwtUser.getApis()
                );
                if (ObjUtil.isNotNull(userDetails)) {
                    var authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    var securityContext = SecurityContextHolder.getContext();
                    securityContext.setAuthentication(authentication);
                    SecurityContextHolder.setContext(securityContext);
                    securityContextRepository.saveContext(securityContext, request, response);
                }
            }

        }
        filterChain.doFilter(request, response);
    }

}